package com.supply.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.supply.pojo.Department;
import com.supply.pojo.ResultBean;
import com.supply.req.DepartmentReq;
import com.supply.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;

    @GetMapping("/list")
    public ResultBean list(DepartmentReq departmentReq){
        PageHelper.startPage(departmentReq.getPageNum(),departmentReq.getPageSize());
        List<Department> departments = departmentService.queryByCondition(departmentReq);
        return ResultBean.success(new PageInfo(departments));
    }

    @GetMapping("/queryAll")
    public ResultBean queryAll(){
        return ResultBean.success(departmentService.queryByCondition(null));
    }

    @PostMapping("/saveOrUpdate")
    public ResultBean saveOrUpdate(@RequestBody Department department){
        System.out.println("新增或修改的数据：" + department);
        int rs = departmentService.saveOrUpdate(department);
        return rs >= 1 ? ResultBean.success() : ResultBean.error("部门名称已存在或服务器异常");
    }

    @DeleteMapping("/delete/{id}")
    public ResultBean delete(@PathVariable("id") Long id){
        System.out.println("要删除的部门id：" + id);
        int rs = departmentService.deleteById(id);
        return rs >= 1 ? ResultBean.success() : ResultBean.error("该部门存在下属员工或服务器异常，删除失败");
    }
}
